var com = com||{};

com.init = function (){
	let scale = 1;
	if(window.innerWidth < 992)
		scale =	(window.innerWidth - 10) / 507;
	com.width			=	507 * scale;
	com.height			=	567 * scale;
	com.spaceX			=	57 * scale;
	com.spaceY			=	57 * scale;
	com.pointStartX		=	23 * scale + 5;
	com.pointStartY		=	23 * scale + 5;
	com.chessWidth		=	54 * scale;
	com.chessHeight		=	54 * scale;
	com.chessWidth		=	54 * scale;
	com.chessHeight		=	54 * scale;
	com.dotWidth		=	12 * scale;
	com.dotHeight		=	12 * scale;
	com.canvas			=	document.getElementById("canvas");
	com.ct				=	com.canvas.getContext("2d") ;
	com.canvas.width	=	com.width + 10;
	com.canvas.height	=	com.height + 10;
	com.childList		=	com.childList||[];
	com.loadImages();
}
com.get = function (id){
	return document.getElementById(id)
}

window.onload = function(){  
	com.bg=new com.class.Bg();
	com.dot = new com.class.Dot();
	com.pane=new com.class.Pane();
	com.pane.isShow=false;
	
	com.childList=[com.bg,com.pane];	
	com.mans={};
	com.createMans(com.initMapRed);
	com.childList.push(com.dot);
	com.bg.show();
	
	let lastIp = localStorage.getItem("ip");
	if(!lastIp)
		lastIp = "localhost";
	com.get("ipInput").value = lastIp;
	com.get("connectServer").onclick=()=>{
		let ip = com.get("ipInput").value;
		net.connect(ip);
		localStorage.setItem("ip",ip);
	};
	com.get("createRoom").onclick=()=>{
		net.send(JSON.stringify({_:"createRoom", type:"chess", count:"2"}));
	};
	com.get("joinRoom").onclick=()=>{
		net.send(JSON.stringify({_:"getRoom", type:"chess"}));
	};
	com.get("quitRoom").onclick=()=>{
		if(net.isInRoom){
			net.isInRoom = false;
			net.send(JSON.stringify({_:"quitRoom"}));
			if(net.isHost)
				com.log("你解散了房间");
			else
				com.log("你离开了房间");
		}else{
			alert("你不在房间内");
		}
	};
	com.get("startGame").onclick=()=>{
		if(net.isInRoom){
			if(play.selfReady)
				alert("你已经准备过了");
			else
				net.send(JSON.stringify({_:"ready", user:net.userId}));
		}else{
			alert("你不在房间内");
		}
	};
	com.get("sendChat").onclick=()=>{
		if(net.isInRoom){
			net.send(JSON.stringify({_:"chat", user:net.userId, chat:com.get("chatInput").value}));
			com.get("chatInput").value = "";
		}else{
			alert("你不在房间内");
		}
	};
	com.get("retract").onclick=()=>{
		if(net.isInRoom){
			if(play.isPlay && play.my != play.turn && play.lastMove){
				net.send(JSON.stringify({_:"retract", user:net.userId}));
			}
		}else{
			alert("你不在房间内");
		}
	};
	com.get("createRoomCancel").onclick=()=>{
		net.isInRoom=false;
		com.get('createRoomDlg').close();
		net.send(JSON.stringify({_:'quitRoom'}));
		com.log("你解散了房间");
	};
}

//载入图片
com.loadImages = function(){
	
	//绘制棋盘
	com.bgImg = new Image();
	com.bgImg.src  = "img/bg.png";
	
	//提示点
	com.dotImg = new Image();
	com.dotImg.src  = "img/dot.png";
	
	//棋子
	for (var i in com.args){
		com[i] = {};
		com[i].img = new Image();
		com[i].img.src = "img/"+ com.args[i].img +".png";
	}
	
	//棋子外框
	com.paneImg = new Image();
	com.paneImg.src  = "img/box.png";
}

//显示列表
com.show = function (){
	com.ct.clearRect(0, 0, com.canvas.width, com.canvas.height);  
	for (var i=0; i<com.childList.length ; i++){
		com.childList[i].show();
	}
}

//显示移动的棋子外框
com.showPane  = function (x,y,newX,newY){
	com.pane.isShow=true;
	com.pane.x= x ;
	com.pane.y= y ;
	com.pane.newX= newX ;
	com.pane.newY= newY ;
}

//生成map里面有的棋子
com.createMans = function(map){
	for (var i=0; i<map.length; i++){
		for (var n=0; n<map[i].length; n++){
			var key = map[i][n];
			if (key){
				com.mans[key]=new com.class.Man(key);
				com.mans[key].x=n;
				com.mans[key].y=i;
				com.childList.push(com.mans[key])
			}
		}
	}
}

//获取元素距离页面左侧的距离
com.getDomXY = function (dom){
	var left = dom.offsetLeft;
	var top = dom.offsetTop;
	var current = dom.offsetParent;
	while (current !== null){
		left += current.offsetLeft;
		top += current.offsetTop;
		current = current.offsetParent;
	}
	return {x:left,y:top};
}

//二维数组克隆
com.arr2Clone = function (arr){
	var newArr=[];
	for (var i=0; i<arr.length ; i++){	
		newArr[i] = arr[i].slice();
	}
	return newArr;
}
//把坐标生成着法
com.createMove = function (man,newX,newY,eat){
	var h = man.text;
	if (man.my===play.my){
		newX=8-newX;
		h+= 9-man.x;
		if (newY > man.y) {
			h+= "退";
			if (man.value == "m" || man.value == "s" || man.value == "x"){
				h+= newX+1;
			}else {
				h+= newY-man.y;
			}
		}else if (newY < man.y) {
			h+= "进";
			if (man.value == "m" || man.value == "s" || man.value == "x"){
				h+= newX+1;
			}else {
				h+= man.y-newY;
			}
		}else {
			h+= "平";
			h+= newX+1;
		}
	}else{
		h+= man.x+1;
		if (newY > man.y) {
			h+= "进";
			if (man.value == "m" || man.value == "s" || man.value == "x"){
				h+= newX+1;
			}else {
				h+= newY-man.y;
			}
		}else if (newY < man.y) {
			h+= "退";
			if (man.value == "m" || man.value == "s" || man.value == "x"){
				h+= newX+1;
			}else {
				h+= man.y-newY;
			}
		}else {
			h+= "平";
			h+= newX+1;
		}
	}
	if(eat)
		h+= "吃"+com.mans[eat].text;
	return h;
}
com.initMapRed = [
	['C0','M0','X0','S0','J0','S1','X1','M1','C1'],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	[    ,'P0',    ,    ,    ,    ,    ,'P1',    ],
	['Z0',    ,'Z1',    ,'Z2',    ,'Z3',    ,'Z4'],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	['z0',    ,'z1',    ,'z2',    ,'z3',    ,'z4'],
	[    ,'p0',    ,    ,    ,    ,    ,'p1',    ],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	['c0','m0','x0','s0','j0','s1','x1','m1','c1']
];

com.initMapBlack = [
	['c1','m1','x1','s1','j0','s0','x0','m0','c0'],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	[    ,'p1',    ,    ,    ,    ,    ,'p0',    ],
	['z4',    ,'z3',    ,'z2',    ,'z1',    ,'z0'],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	['Z4',    ,'Z3',    ,'Z2',    ,'Z1',    ,'Z0'],
	[    ,'P1',    ,    ,    ,    ,    ,'P0',    ],
	[    ,    ,    ,    ,    ,    ,    ,    ,    ],
	['C1','M1','X1','S1','J0','S0','X0','M0','C0']
];


com.keys = {
	"c0":"c","c1":"c",
	"m0":"m","m1":"m",
	"x0":"x","x1":"x",
	"s0":"s","s1":"s",
	"j0":"j",
	"p0":"p","p1":"p",
	"z0":"z","z1":"z","z2":"z","z3":"z","z4":"z","z5":"z",
	
	"C0":"c","C1":"C",
	"M0":"M","M1":"M",
	"X0":"X","X1":"X",
	"S0":"S","S1":"S",
	"J0":"J",
	"P0":"P","P1":"P",
	"Z0":"Z","Z1":"Z","Z2":"Z","Z3":"Z","Z4":"Z","Z5":"Z",
}

//棋子能走的着点
com.bylaw ={}
//车
com.bylaw.c = function (x,y,map,my){
	var d=[];
	//左侧检索
	for (var i=x-1; i>= 0; i--){
		if (map[y][i]) {
			if (com.mans[map[y][i]].my!=my) d.push([i,y]);
			break
		}else{
			d.push([i,y]);
		}
	}
	//右侧检索
	for (var i=x+1; i <= 8; i++){
		if (map[y][i]) {
			if (com.mans[map[y][i]].my!=my) d.push([i,y]);
			break
		}else{
			d.push([i,y]);
		}
	}
	//上检索
	for (var i = y-1 ; i >= 0; i--){
		if (map[i][x]) {
			if (com.mans[map[i][x]].my!=my) d.push([x,i]);
			break
		}else{
			d.push([x,i]);
		}
	}
	//下检索
	for (var i = y+1 ; i<= 9; i++){
		if (map[i][x]) {
			if (com.mans[map[i][x]].my!=my) d.push([x,i]);
			break
		}else{
			d.push([x,i]);
		}
	}
	return d;
}

//马
com.bylaw.m = function (x,y,map,my){
	var d=[];
		//1点
		if ( y-2>= 0 && x+1<= 8 && !play.map[y-1][x] &&(!com.mans[map[y-2][x+1]] || com.mans[map[y-2][x+1]].my!=my)) d.push([x+1,y-2]);
		//2点
		if ( y-1>= 0 && x+2<= 8 && !play.map[y][x+1] &&(!com.mans[map[y-1][x+2]] || com.mans[map[y-1][x+2]].my!=my)) d.push([x+2,y-1]);
		//4点
		if ( y+1<= 9 && x+2<= 8 && !play.map[y][x+1] &&(!com.mans[map[y+1][x+2]] || com.mans[map[y+1][x+2]].my!=my)) d.push([x+2,y+1]);
		//5点
		if ( y+2<= 9 && x+1<= 8 && !play.map[y+1][x] &&(!com.mans[map[y+2][x+1]] || com.mans[map[y+2][x+1]].my!=my)) d.push([x+1,y+2]);
		//7点
		if ( y+2<= 9 && x-1>= 0 && !play.map[y+1][x] &&(!com.mans[map[y+2][x-1]] || com.mans[map[y+2][x-1]].my!=my)) d.push([x-1,y+2]);
		//8点
		if ( y+1<= 9 && x-2>= 0 && !play.map[y][x-1] &&(!com.mans[map[y+1][x-2]] || com.mans[map[y+1][x-2]].my!=my)) d.push([x-2,y+1]);
		//10点
		if ( y-1>= 0 && x-2>= 0 && !play.map[y][x-1] &&(!com.mans[map[y-1][x-2]] || com.mans[map[y-1][x-2]].my!=my)) d.push([x-2,y-1]);
		//11点
		if ( y-2>= 0 && x-1>= 0 && !play.map[y-1][x] &&(!com.mans[map[y-2][x-1]] || com.mans[map[y-2][x-1]].my!=my)) d.push([x-1,y-2]);

	return d;
}

//相
com.bylaw.x = function (x,y,map,my){
	var d=[];
	if (my===play.my){ //红方
		//4点半
		if ( y+2<= 9 && x+2<= 8 && !play.map[y+1][x+1] && (!com.mans[map[y+2][x+2]] || com.mans[map[y+2][x+2]].my!=my)) d.push([x+2,y+2]);
		//7点半
		if ( y+2<= 9 && x-2>= 0 && !play.map[y+1][x-1] && (!com.mans[map[y+2][x-2]] || com.mans[map[y+2][x-2]].my!=my)) d.push([x-2,y+2]);
		//1点半
		if ( y-2>= 5 && x+2<= 8 && !play.map[y-1][x+1] && (!com.mans[map[y-2][x+2]] || com.mans[map[y-2][x+2]].my!=my)) d.push([x+2,y-2]);
		//10点半
		if ( y-2>= 5 && x-2>= 0 && !play.map[y-1][x-1] && (!com.mans[map[y-2][x-2]] || com.mans[map[y-2][x-2]].my!=my)) d.push([x-2,y-2]);
	}else{
		//4点半
		if ( y+2<= 4 && x+2<= 8 && !play.map[y+1][x+1] && (!com.mans[map[y+2][x+2]] || com.mans[map[y+2][x+2]].my!=my)) d.push([x+2,y+2]);
		//7点半
		if ( y+2<= 4 && x-2>= 0 && !play.map[y+1][x-1] && (!com.mans[map[y+2][x-2]] || com.mans[map[y+2][x-2]].my!=my)) d.push([x-2,y+2]);
		//1点半
		if ( y-2>= 0 && x+2<= 8 && !play.map[y-1][x+1] && (!com.mans[map[y-2][x+2]] || com.mans[map[y-2][x+2]].my!=my)) d.push([x+2,y-2]);
		//10点半
		if ( y-2>= 0 && x-2>= 0 && !play.map[y-1][x-1] && (!com.mans[map[y-2][x-2]] || com.mans[map[y-2][x-2]].my!=my)) d.push([x-2,y-2]);
	}
	return d;
}

//士
com.bylaw.s = function (x,y,map,my){
	var d=[];
	if (my===play.my){ //红方
		//4点半
		if ( y+1<= 9 && x+1<= 5 && (!com.mans[map[y+1][x+1]] || com.mans[map[y+1][x+1]].my!=my)) d.push([x+1,y+1]);
		//7点半
		if ( y+1<= 9 && x-1>= 3 && (!com.mans[map[y+1][x-1]] || com.mans[map[y+1][x-1]].my!=my)) d.push([x-1,y+1]);
		//1点半
		if ( y-1>= 7 && x+1<= 5 && (!com.mans[map[y-1][x+1]] || com.mans[map[y-1][x+1]].my!=my)) d.push([x+1,y-1]);
		//10点半
		if ( y-1>= 7 && x-1>= 3 && (!com.mans[map[y-1][x-1]] || com.mans[map[y-1][x-1]].my!=my)) d.push([x-1,y-1]);
	}else{
		//4点半
		if ( y+1<= 2 && x+1<= 5 && (!com.mans[map[y+1][x+1]] || com.mans[map[y+1][x+1]].my!=my)) d.push([x+1,y+1]);
		//7点半
		if ( y+1<= 2 && x-1>= 3 && (!com.mans[map[y+1][x-1]] || com.mans[map[y+1][x-1]].my!=my)) d.push([x-1,y+1]);
		//1点半
		if ( y-1>= 0 && x+1<= 5 && (!com.mans[map[y-1][x+1]] || com.mans[map[y-1][x+1]].my!=my)) d.push([x+1,y-1]);
		//10点半
		if ( y-1>= 0 && x-1>= 3 && (!com.mans[map[y-1][x-1]] || com.mans[map[y-1][x-1]].my!=my)) d.push([x-1,y-1]);
	}
	return d;
		
}

//将
com.bylaw.j = function (x,y,map,my){
	var d=[];
	var isNull=(function (y1,y2){
		var y1=com.mans["j0"].y;
		var x1=com.mans["J0"].x;
		var y2=com.mans["J0"].y;
		if(y1>y2){
			for (var i=y1-1; i>y2; i--){
				if (map[i][x1]) return false;
			}
		}
		else{
			for (var i=y1+1; i<y2; i++){
				if (map[i][x1]) return false;
			}
		}
		return true;
	})();
	
	if (my===play.my){ //己方
		//下
		if ( y+1<= 9  && (!com.mans[map[y+1][x]] || com.mans[map[y+1][x]].my!=my)) d.push([x,y+1]);
		//上
		if ( y-1>= 7 && (!com.mans[map[y-1][x]] || com.mans[map[y-1][x]].my!=my)) d.push([x,y-1]);
		
	}else{
		//下
		if ( y+1<= 2  && (!com.mans[map[y+1][x]] || com.mans[map[y+1][x]].my!=my)) d.push([x,y+1]);
		//上
		if ( y-1>= 0 && (!com.mans[map[y-1][x]] || com.mans[map[y-1][x]].my!=my)) d.push([x,y-1]);
	}
	//老将对老将的情况
	if ( com.mans["j0"].x == com.mans["J0"].x &&isNull){
		if(my==1)
			d.push([com.mans["J0"].x,com.mans["J0"].y]);
		else
			d.push([com.mans["j0"].x,com.mans["j0"].y]);
	}

	//右
	if ( x+1<= 5  && (!com.mans[map[y][x+1]] || com.mans[map[y][x+1]].my!=my)) d.push([x+1,y]);
	//左
	if ( x-1>= 3 && (!com.mans[map[y][x-1]] || com.mans[map[y][x-1]].my!=my))d.push([x-1,y]);
	return d;
}

//炮
com.bylaw.p = function (x,y,map,my){
	var d=[];
	//左侧检索
	var n=0;
	for (var i=x-1; i>= 0; i--){
		if (map[y][i]) {
			if (n==0){
				n++;
				continue;
			}else{
				if (com.mans[map[y][i]].my!=my) d.push([i,y]);
				break	
			}
		}else{
			if(n==0) d.push([i,y])	
		}
	}
	//右侧检索
	var n=0;
	for (var i=x+1; i <= 8; i++){
		if (map[y][i]) {
			if (n==0){
				n++;
				continue;
			}else{
				if (com.mans[map[y][i]].my!=my) d.push([i,y]);
				break	
			}
		}else{
			if(n==0) d.push([i,y])	
		}
	}
	//上检索
	var n=0;
	for (var i = y-1 ; i >= 0; i--){
		if (map[i][x]) {
			if (n==0){
				n++;
				continue;
			}else{
				if (com.mans[map[i][x]].my!=my) d.push([x,i]);
				break	
			}
		}else{
			if(n==0) d.push([x,i])	
		}
	}
	//下检索
	var n=0;
	for (var i = y+1 ; i<= 9; i++){
		if (map[i][x]) {
			if (n==0){
				n++;
				continue;
			}else{
				if (com.mans[map[i][x]].my!=my) d.push([x,i]);
				break	
			}
		}else{
			if(n==0) d.push([x,i])	
		}
	}
	return d;
}

//卒
com.bylaw.z = function (x,y,map,my){
	var d=[];
	if (my===play.my){ //己方
		//上
		if ( y-1>= 0 && (!com.mans[map[y-1][x]] || com.mans[map[y-1][x]].my!=my)) d.push([x,y-1]);
		//右
		if ( x+1<= 8 && y<=4  && (!com.mans[map[y][x+1]] || com.mans[map[y][x+1]].my!=my)) d.push([x+1,y]);
		//左
		if ( x-1>= 0 && y<=4 && (!com.mans[map[y][x-1]] || com.mans[map[y][x-1]].my!=my))d.push([x-1,y]);
	}else{
		//下
		if ( y+1<= 9  && (!com.mans[map[y+1][x]] || com.mans[map[y+1][x]].my!=my)) d.push([x,y+1]);
		//右
		if ( x+1<= 8 && y>=5  && (!com.mans[map[y][x+1]] || com.mans[map[y][x+1]].my!=my)) d.push([x+1,y]);
		//左
		if ( x-1>= 0 && y>=5 && (!com.mans[map[y][x-1]] || com.mans[map[y][x-1]].my!=my))d.push([x-1,y]);
	}
	
	return d;
}


//棋子们
com.args={
	//红子 中文/图片地址/阵营
	'c':{text:"红车", img:'r_c', my:1 ,bl:"c"},
	'm':{text:"红马", img:'r_m', my:1 ,bl:"m"},
	'x':{text:"红相", img:'r_x', my:1 ,bl:"x"},
	's':{text:"红仕", img:'r_s', my:1 ,bl:"s"},
	'j':{text:"红帅", img:'r_j', my:1 ,bl:"j"},
	'p':{text:"红炮", img:'r_p', my:1 ,bl:"p"},
	'z':{text:"红兵", img:'r_z', my:1 ,bl:"z"},
	
	//黑子
	'C':{text:"黑车", img:'b_c', my:-1 ,bl:"c"},
	'M':{text:"黑马", img:'b_m', my:-1 ,bl:"m"},
	'X':{text:"黑象", img:'b_x', my:-1 ,bl:"x"},
	'S':{text:"黑士", img:'b_s', my:-1 ,bl:"s"},
	'J':{text:"黑将", img:'b_j', my:-1 ,bl:"j"},
	'P':{text:"黑炮", img:'b_p', my:-1 ,bl:"p"},
	'Z':{text:"黑卒", img:'b_z', my:-1 ,bl:"z"}
};

com.class = com.class || {} //类
com.class.Man = function (key, x, y){
	this.pater = key.slice(0,1);
	var o=com.args[this.pater]
	this.x = x||0;   
    this.y = y||0;
	this.key = key;
	this.my = o.my;
	this.text = o.text;
	this.value = o.bl;
	this.isShow = true;
	this.alpha = 1;
	this.ps = []; //着点
	
	this.show = function (){
		if (this.isShow) {
			if(this.key == com.moveKey){
				let dx = Math.abs(com.moveX - this.x);
				let dy = Math.abs(com.moveY - this.y);
				let sx = Math.sign(com.moveX - this.x);
				let sy = Math.sign(com.moveY - this.y);
				if(dx == 0 || dy == 0 || dx == dy){
					this.x += 0.5 * sx;
					this.y += 0.5 * sy;
				}else if(dx < dy){
					this.x += 0.5 * sx * dx / dy;
					this.y += 0.5 * sy;
				}else{
					this.x += 0.5 * sx;
					this.y += 0.5 * sy * dy / dx;
				}
				if(Math.abs(this.x - com.moveX) < 0.1 && Math.abs(this.y - com.moveY) < 0.1){
					this.x = com.moveX;
					this.y = com.moveY;
					com.moveKey = false;
				}
			}
			com.ct.save();
			com.ct.globalAlpha = this.alpha;
			com.ct.drawImage(com[this.pater].img,com.spaceX * this.x + com.pointStartX - com.chessWidth / 2,
				com.spaceY *  this.y +com.pointStartY - com.chessHeight / 2,
				com.chessWidth, com.chessHeight);
			com.ct.restore(); 
		}
	}
	
	this.bl = function (map){
		var map = map || play.map;
		return com.bylaw[o.bl](this.x,this.y,map,this.my);
	}
}

com.class.Bg = function (){
	this.isShow = true;
	this.show = function (){
		if (this.isShow) com.ct.drawImage(com.bgImg, 5, 5, com.width, com.height);
	}
}
com.class.Pane = function (){
	this.isShow = true;
	this.show = function (){
		if (this.isShow) {
			com.ct.drawImage(com.paneImg, com.spaceX * this.x + com.pointStartX - com.chessWidth / 2, com.spaceY *  this.y + com.pointStartY - com.chessHeight / 2, com.chessWidth, com.chessHeight);
			com.ct.drawImage(com.paneImg, com.spaceX * this.newX + com.pointStartX - com.chessWidth / 2, com.spaceY *  this.newY + com.pointStartY - com.chessHeight / 2, com.chessWidth, com.chessHeight);
		}
	}
}

com.class.Dot = function (){
	this.isShow = true;
	this.dots=[]
	this.show = function (){
		for (var i=0; i<this.dots.length;i++){
			if (this.isShow) com.ct.drawImage(com.dotImg, com.spaceX * this.dots[i][0] + com.pointStartX - com.dotWidth / 2,com.spaceY *  this.dots[i][1] + com.pointStartY - com.dotHeight / 2, com.dotWidth, com.dotHeight);
		}
	}
}

com.log = function(msg){
	let div = document.createElement("div");
	div.innerHTML = msg;
	let info = com.get("info");
	if(info.childElementCount == 0)
		info.appendChild(div);
	else{
		if(info.childElementCount > 3)
			info.removeChild(info.lastChild);
		info.insertBefore(div, info.firstChild);
	}
}

com.init();